package com.huilian.iotbox.mqtt.server.base.handler;

import com.huilian.iotbox.aliyun.service.PubService;
import com.huilian.iotbox.mqtt.server.base.service.BaudService;
import com.huilian.iotbox.mqtt.server.base.service.DeviceService;
import com.huilian.iotbox.data.dto.DeviceDto;
import com.huilian.iotbox.data.po.Baud;
import com.huilian.iotbox.data.utils.IotBoxUtil;
import com.huilian.iotbox.data.vo.DeviceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * BoxParamsQueryHandler
 * 26.2、查询支付盒子参数（支付盒子to服务器）
 *
 * @Author mineChen
 * @Date 2021/8/28 上午 11:32
 */
@Slf4j
@Service("messageHandleService29")
public class BoxParamsQueryHandler implements MessageHandlerStrategy {

    @Value("${huilian.iot.apiProductKey}")
    private String apiProductKey;
    @Autowired
    private PubService pubService;
    @Autowired
    private BaudService baudService;
    @Autowired
    private DeviceService deviceService;

    @Override
    public void process(String content, String deviceNo, String productKey, Integer serviceProviderCode) {

        /**
         * 金
         * AA2C0129018025000008000000320019003839383630343835313932304630303135333032001E001E00140000E8DD
         * AA2C0129010096000008000000320032003839383630343737313032313730303332303236 011E013200320000 8EDD
         *
         * 莫
         * AA2C0129C90096000008000000320032003839383630343336313032303830303930383236001E0000000000004DDD
         */

        final Integer firmwareVersion = IotBoxUtil.singleHex2Int(content.substring(8, 10));
        final Integer baudCode = IotBoxUtil.singleHex2Int(IotBoxUtil.reverseHex(content.substring(10, 18)));
        final Integer dataBit = IotBoxUtil.singleHex2Int(content.substring(18, 20));
        final Integer parityBit = IotBoxUtil.singleHex2Int(content.substring(20, 22));
        final Integer stopBit = IotBoxUtil.singleHex2Int(content.substring(22, 24));
        final Integer level = IotBoxUtil.singleHex2Int(content.substring(24, 26));
        final Integer gapLength = IotBoxUtil.singleHex2Int(IotBoxUtil.reverseHex(content.substring(26, 30)));
        final Integer pulseLength = IotBoxUtil.singleHex2Int(IotBoxUtil.reverseHex(content.substring(30, 34)));
        String iccId;
        StringBuilder iccIdStringBuilder = new StringBuilder();
        try {
            // 忽略安卓板兑币机这个的bug
            iccId = content.substring(34, 74).toUpperCase();
            iccIdStringBuilder = new StringBuilder(IotBoxUtil.convertHexToString(iccId));
        } catch (Exception e) {
            e.printStackTrace();
        }

        final Integer pulseSwitchState = IotBoxUtil.singleHex2Int(content.substring(74, 76));
        final Integer heartTime = IotBoxUtil.singleHex2Int(content.substring(76, 78));
        final Integer lotteryPattern = IotBoxUtil.singleHex2Int(content.substring(78, 80));
        final Integer gapLengthByChuLi = IotBoxUtil.singleHex2Int(IotBoxUtil.reverseHex(content.substring(80, 84)));
        final Integer pulseLengthByChuLi = IotBoxUtil.singleHex2Int(IotBoxUtil.reverseHex(content.substring(84, 88)));
//        final Integer yuLiu = IotBoxUtil.singleHex2Int(content.substring(92, 94));

        log.info("支付盒子参数: 版本：{}, 波特率：{}, 数据位: {}, 校验位: {}, 停止位: {}, 向外投币电平: {}, 脉冲间隔: {}, 脉冲宽度: {}, SIM ICCID: {}, 脉冲开关状态: {}, 心跳时间: {}, 出礼模式: {}, 出礼脉冲间隔: {}, 出礼脉冲宽度: {}",
                firmwareVersion, baudCode, dataBit, parityBit, stopBit, level, gapLength, pulseLength, iccIdStringBuilder, pulseSwitchState, heartTime, lotteryPattern, gapLengthByChuLi, pulseLengthByChuLi);

        // 更新盒子设备状态
        DeviceVo deviceVo = deviceService.findOneDeviceByDeviceNo(deviceNo);
        // API盒子需要发给中间件
        if (deviceVo.getIsApi()){
            pubService.pub(content, deviceNo, apiProductKey);
        }
        if (StringUtils.isEmpty(deviceVo)) {
            log.warn(String.format("保存盒子参数找不到%s设备，%s", deviceNo, content));
            return;
        }

        DeviceDto deviceDto = new DeviceDto();
        Baud baud = baudService.findOneBaudByCode(baudCode);
        if (StringUtils.isEmpty(baud)) {
            log.warn(String.format("保存盒子参数找不到%s设备对应波特率参数，%s", deviceNo, content.substring(10, 18)));
        } else {
            deviceDto.setBaudId(baud.getId());
        }

        deviceDto.setId(deviceVo.getId());
        deviceDto.setFirmwareVersion(firmwareVersion);
        deviceDto.setDataBit(dataBit);
        deviceDto.setParityBit(parityBit);
        deviceDto.setStopBit(stopBit);
        deviceDto.setLevel(level);
        deviceDto.setSIM_ICC_ID(String.valueOf(iccIdStringBuilder));
        deviceDto.setPulseSwitchState(pulseSwitchState == 1 ? true : false);
        deviceDto.setHeartbeatTime(heartTime);
        deviceDto.setRitualModel(lotteryPattern);
        deviceDto.setGapLength(gapLength);
        deviceDto.setPulseLength(pulseLength);
        deviceDto.setOutgoingGapLength(gapLengthByChuLi);
        deviceDto.setOutgoingPulseLength(pulseLengthByChuLi);
        deviceService.updateDeviceById(deviceDto);
    }
}
